package com.yrot.admin.service.impl;

import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yrot.admin.entity.SysExpert;
import com.yrot.admin.entity.SysQuestionBank;
import com.yrot.admin.entity.SysQuestions;
import com.yrot.admin.excel.SysQuestionsImport;
import com.yrot.admin.mapper.SysQuestionBankMapper;
import com.yrot.admin.mapper.SysQuestionsMapper;
import com.yrot.admin.service.ISysQuestionsService;
import com.yrot.common.result.R;
import com.yrot.common.utils.EasyExcelUtil;
import com.yrot.common.utils.FullHalfAngle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hemin
 * @since 2019-04-02
 */
@Service
@Slf4j
public class SysQuestionsServiceImpl extends ServiceImpl<SysQuestionsMapper, SysQuestions> implements ISysQuestionsService {

    @Autowired
    SysQuestionBankMapper sysQuestionBankMapper;
    @Autowired
    SysQuestionsMapper sysQuestionsMapper;
    @Override
    public List<SysQuestions> findRandQuestions(Integer trainId, Integer trainNum) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("trainId",trainId);
        map.put("trainNum",trainNum);
        return sysQuestionsMapper.findRandQuestions(map);
    }
    @Override
    @Transactional
    public R upload(MultipartFile file) {
        try {
            List<Object> objects = EasyExcelUtil.readExcelWithModel(file.getInputStream(), SysQuestionsImport.class, ExcelTypeEnum.XLSX);
            ArrayList<SysQuestions> questions = new ArrayList<>();
            for (int i = 0; i < objects.size(); i++) {
                int index = i+2;
                SysQuestionsImport questionsImport = (SysQuestionsImport) objects.get(i);
                SysQuestions sysQuestions = new SysQuestions();
                Map<String, Integer> bankMap = getBankMap();
                BeanUtils.copyProperties(questionsImport,sysQuestions);
                Integer bankId = bankMap.get(questionsImport.getBankName());
                if(bankId == null){
                    return R.error("第"+index+"行的题库不存在");
                }
                switch (questionsImport.getQuestionType()){
                    case "判断题" : sysQuestions.setQuestionType(0); break;
                    case "单选题" : sysQuestions.setQuestionType(1); break;
                    case "多选题" : sysQuestions.setQuestionType(2); break;
                    default : return R.error("第"+index+"行题目类型格式错误");
                }
                sysQuestions.setBankId(bankId);
                //验证
                R r = sysQuestionsValid(index, sysQuestions);
                if(!r.get("code").equals(0)){
                   return r;
                }
                questions.add(sysQuestions);
            }
            saveBatch(questions);
        } catch (IOException e) {
            log.error("题目导入失败",e);
            return R.error("题目导入失败");
        }
        return R.ok();
    }

    private Map<String,Integer> getBankMap(){
        HashMap<String, Integer> bankMap = new HashMap<>();
        QueryWrapper<SysQuestionBank> bankQueryWrapper = new QueryWrapper<>();
        SysExpert sysExpert = (SysExpert) SecurityUtils.getSubject().getPrincipal();
        bankQueryWrapper.eq("expert_id",sysExpert.getExpertId());
        List<SysQuestionBank> sysQuestionBanks = sysQuestionBankMapper.selectList(bankQueryWrapper);
        sysQuestionBanks.forEach(bank -> {
            bankMap.put(bank.getBankName(),bank.getBankId());
        });
        return bankMap;
    }

    /**
     * 验证
     * @param index 行数
     * @param sysQuestions 题目信息
     * @return 是否成功
     */
    private R sysQuestionsValid(int index,SysQuestions sysQuestions){
        String questionAnswer = sysQuestions.getQuestionAnswer();
        if(StringUtils.isEmpty(sysQuestions.getQuestionContent())){
            return R.error("第"+index+"行题目内容不能为空");
        }
        if(StringUtils.isEmpty(questionAnswer)){
            return R.error("第"+index+"行题目答案不能为空");
        }
        //全角转半角
        sysQuestions.setQuestionAnswer(FullHalfAngle.ToDBC(questionAnswer));
        if(StringUtils.isEmpty(sysQuestions.getOptionA())){
            return R.error("第"+index+"行题目选项A不能为空");
        }
        if(StringUtils.isEmpty(sysQuestions.getOptionB())){
            return R.error("第"+index+"行题目选项B不能为空");
        }
        String answer = sysQuestions.getQuestionAnswer();
        if(answer.length() <= 1){
            String pattern = "[A-F]";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(answer);
            if(!m.matches()){
                return R.error("第"+index+"行题目答案格式错误");
            }
        }else{
            String[] split = answer.split(",");
            if(split==null || (split.length-1) != ((answer.length()-1)/2)){
                return R.error("第"+index+"行题目答案格式错误");
            }
        }
        return R.ok();
    }

    @Override
    public void export() {

    }
}
